// pages/post/post.js
const app = getApp();
const request = require('../../utils/request.js');
const config = require('../../utils/config');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorTheme: app.globalData.colorTheme,
    postId: -1,
    postInfo: [],
    pageNum: 1,
    pageSize: 10,
    commentList: [],
    isResult: true,
    commentTotal: 0,
    keyBoardHeight: 0,
    isFocus: false,
    clearValue: '',
    replyIndex: -1,
    intoView: ''
  },

  /**
   * 获取帖子详情
   */
  getPostInfo() {
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'index/post/detail/' + this.data.postId;
    wx.showLoading({
      title: '加载ing'
    });
    request.requestGetApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        this.setData({
          postInfo: res.data
        })
      }else{
        wx.showModal({
          title: '提示',
          content: "帖子已被删除！",
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#3CC51F',
          success: (result) => {
            if(result.confirm){
              wx.navigateBack({
                delta: 1
              });
            }
          }
        });
      }
    }).catch(err=>{
      app.failFun(err);
    })
  },

  /**
   * 获取帖子评论列表
   */
  getCommentList(pageNum, pageSize){
    let that = this;
    let url = config.SERVER_URL + 'comment/listCommentOfPost/' + this.data.postId;
    let token = wx.getStorageSync('token');
    let params = {
      pageNum,
      pageSize
    }
    wx.showLoading({
      title: '加载ing'
    });
    request.requestGetApi(url, token, params, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        let isResult = res.data.rows.length >= pageSize;
        that.setData({
          isResult,
          commentTotal: res.data.total,
          commentList: that.data.commentList.concat(res.data.rows)
        })
      }
    }).catch(err=>{
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 点赞帖子或取消点赞帖子
   */
  likeOrunLikePost(){
    if(!app.checkedUserLoading()){
      return;
    }
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL;
    let postInfo = this.data.postInfo;
    if(postInfo.like){
      url += 'post/unLike/' + this.data.postId;
      postInfo.likeCount--;
    }else{
      url += 'post/like/' + this.data.postId;
      postInfo.likeCount++;
    }
    postInfo.like = !postInfo.like;
    request.requestPostApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          postInfo
        });
      }
    }).catch(err=>{
      app.failFun(err);
    })
  },

  /**
   * 收藏帖子或取消收藏帖子
   */
  collectOrCancelPost(){
    if(!app.checkedUserLoading()){
      return;
    }
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL;
    let postInfo = that.data.postInfo;
    if(postInfo.collect){
      url += 'post/cancelCollect/' + this.data.postId;
    }else{
      url += 'post/collect/' + this.data.postId;
    }
    postInfo.collect = !postInfo.collect;
    request.requestPostApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          postInfo
        });
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 1500,
        });
      }
    }).catch(err=>{
      app.failFun(err);
    })
  },

  /**
   * 删除帖子
   */
  deletePost(){
    wx.showModal({
      title: '提示',
      content: '确定删除该帖子吗？',
      confirmText: '删除',
      confirmColor: '#e54d42',
      success: (result) => {
        if(result.confirm){
          let token = wx.getStorageSync('token');
          let url = config.SERVER_URL + 'post/delPost/' + this.data.postId;
          request.requestPostApi(url, token, {}, 'application/json').then(res=>{
            if(res.status === config.STATUS_OK){
              wx.showToast({
                title: res.message,
                icon: 'success',
                duration: 1500
              });
              setTimeout(()=>{
                wx.navigateBack({
                  delta: 1
                });
              }, 1000);
            }
          }).catch(err=>{
            app.failFun(err);
          });
        }
      }
    });
  },

  /**
   * 提交评论
   */
  submitComment(e){
    if(!app.checkedUserLoading()){
      return;
    }
    let that = this;
    let params = e.detail.value;
    if(typeof params !== 'object'){
      let content = params;
      params = { content };
    }
    params.postId = this.data.postId;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'comment/toPost';
    wx.showLoading({
      title: '评论中...'
    });
    request.requestPostApi(url, token, params, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          commentList: [],
          clearValue: ''
        });
        that.getCommentList(that.data.pageNum, that.data.pageSize);
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 1500
        });
      }
    }).catch(err=>{
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 评论文本框获得焦点
   */
  focusComment(){
    this.setData({
      isFocus: true
    })
  },

  /**
   * 评论文本框失去焦点
   */
  blurComment(){
    let that = this;
    setTimeout(function() {
      that.setData({
        isFocus: false
      })
    }, 200);
  },

  /**
   * 获取键盘高度变化
   */
  getKeyboardHeight(e){
    this.setData({
      keyBoardHeight: e.detail.height
    });
  },

  /**
   * 跳转到编写帖子页面
   */
  toPublishPost(){
    wx.navigateTo({
      url: '/pages/editor/editor'
    });
  },

  /**
   * 查看回复
   */
  toCommentInfo(e){
    let commentInfo;
    if(e === undefined){
      commentInfo = this.data.commentList[this.data.replyIndex];
    }else{
      commentInfo = this.data.commentList[e.currentTarget.dataset.index];
    }
    let jsonComment = JSON.stringify(commentInfo);
    wx.navigateTo({
      url: './comment/comment?commentInfo=' + jsonComment
    });
    this.hideModal();
  },

  /**
   * 点赞或取消点赞评论
   */
  likeorUnLikeComment(e){
    if(!app.checkedUserLoading()){
      return;
    }
    let commentList = this.data.commentList;
    let commentInfo, index;
    // 判断点赞方式
    if(e !== undefined){
      index = e.currentTarget.dataset.index;
    }else{
      index = this.data.replyIndex;
    }
    commentInfo = this.data.commentList[index];
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL;
    if(commentInfo.like){
      url += 'comment/cancelLikesComment/' + commentInfo.id;
      commentInfo.likes--;
    }else{
      url += 'comment/likesComment/' + commentInfo.id;
      commentInfo.likes++;
    }
    commentInfo.like = !commentInfo.like;
    commentList[index] = commentInfo;
    request.requestPostApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          commentList
        });
        that.hideModal();
      }
    }).catch(err=>{
      app.failFun(err);
    });
  },

  /**
   * 删除自己的评论
   */
  deleteComment(){
    let commentList = this.data.commentList;
    let index = this.data.replyIndex;
    let commentInfo = this.data.commentList[index];
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'comment/delComment/' + commentInfo.id;
    wx.showLoading({
      title: '删除中...'
    });
    commentList.splice(index, 1);
    request.requestPostApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          commentList
        });
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 1500
        });
        that.hideModal();
      }
    }).catch(err=>{
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 编辑帖子
   */
  editorPost(){
    wx.navigateTo({
      url: '/pages/editor/editor?postId=' + this.data.postId
    });
    this.hideModal();
  },

  /**
   * 弹出底部评论操作列表
   */
  showCommentAction(e){
    let index = e.currentTarget.dataset.index;
    this.setData({
      replyIndex: index
    })
    let list = [
      this.data.commentList[index].likes ? '取消点赞' : '点赞',
      '回复'
    ];
    if(this.data.commentList[index].fromUid === this.data.userId){
      list.push('删除');
    };
    wx.showActionSheet({
      itemList: list,
      itemColor: '#000000',
      success: (result)=>{
        if(result.tapIndex === 0){
          this.likeorUnLikeComment();
        }else if(result.tapIndex === 1){
          this.toCommentInfo();
        }else if(result.tapIndex === 2){
          this.deleteComment();
        }
      }
    });
  },


  /**
   * 滚动到评论区
   */
  toComment(){
    this.setData({
      intoView: 'comment'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userId= wx.getStorageSync('userInfo') ? wx.getStorageSync('userInfo').uid : -1;
    this.setData({
      userId,
      postId: options.postId
    });
    if(options.jump){
      this.toComment();
    }
    this.getPostInfo();
    this.getCommentList(this.data.pageNum, this.data.pageSize);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      commentList: [],
      pageNum: 1
    })
    this.getPostInfo();
    this.getCommentList(this.data.pageNum, this.data.pageSize);

    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(!this.data.isResult){
      return;
    }
    let pageNum = this.data.pageNum + 1;
    this.setData({
      pageNum: pageNum
    });
    this.getCommentList(pageNum, this.data.pageSize);
  },

  /**
   * 模态框的显示和隐藏
   */
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    });
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
})